package com.zxl.template.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luliang.shapeutils.DevShapeUtils;
import com.luliang.shapeutils.shape.DevShape;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zxl.template.R;
import com.zxl.template.activity.DocDetailActivity;
import com.zxl.template.base.BaseFrag;
import com.zxl.template.base.IActivity;
import com.zxl.template.constant.constant;
import com.zxl.template.http.JsonCallback;
import com.zxl.template.model.Doc;
import com.zxl.template.model.DocParams;
import com.zxl.template.model.DocRows;
import com.zxl.template.model.MsgEvent;
import com.zxl.zlibrary.tool.LActivityTool;
import com.zxl.zlibrary.tool.LEmptyTool;
import com.zxl.zlibrary.tool.LogTool;
import com.zxl.zlibrary.view.LClearEditText;
import com.zxl.zlibrary.view.statusview.LStatusView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * author : 王新海
 * time   : 2018/11/21.
 * version: 1.0.0
 * desc   :代办理公文
 */
public class AgencyDocPager extends BaseFrag implements IActivity, constant {
    private static final String TAG = "AgencyDocPager";

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.status_view)
    LStatusView statusView;
    private Unbinder unbinder;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.et_search)
    LClearEditText etSearch;


    private RvAdapter rvAdapter;
    private List<DocRows> rowsList = new ArrayList<>();
    private int mPage = 1;
    private int mRows = 10;

    private String mKeyword;
    private int mLastUpdateNum;

    private String mDocType;
    private String flowId;

    public static BaseFrag getInstance() {
        return new AgencyDocPager();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.tab_doc_pager, container, false);
        unbinder = ButterKnife.bind(this, inflate);


        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);

        initView();
        initData();
        initListener();

        //刷新
        EventBus.getDefault().post(new MsgEvent<>("refresh_main", "1"));
    }

    @Override
    public void initView() {
        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.white).line(1, R.color.colorLine).radius(16).into(etSearch);
        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.colorPrimary).line(1, R.color.colorLine).radius(16).into(tvSearch);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvAdapter = new RvAdapter(rowsList);
        recyclerView.setAdapter(rvAdapter);

        statusView.setOnViewRefreshListener(this::initNet);

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MsgEvent<DocParams> event) {
        switch (event.type) {
            case EVENTBUS_AGENCY_DOC_REGRESH_LIST:
                DocParams docParams = event.t;
                if (docParams.isSwitch != null) {
                    mDocType = "1";//1 收文
                    if (docParams.isSwitch) {
                        mDocType = "2";   //2发文
                    }
                }
                flowId = docParams.flowId;
                initNet();
                break;
            case "refresh_doc_list":
                initNet();
                break;
            case EVENTBUS_AGENCY_DOC_REGRESH_ALL:
                flowId = null;
                mDocType = null;
                initNet();
                break;
        }
    }


    @Override
    public void initListener() {
        rvAdapter.setOnItemClickListener((adapter, view, position) -> {
            DocRows item = (DocRows) adapter.getData().get(position);
            Bundle args = new Bundle();
            args.putSerializable("data", item);
            LActivityTool.startActivity(args, DocDetailActivity.class);
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            initNet();
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            loadMore();
        });


        tvSearch.setOnClickListener(v -> {
            mKeyword = Objects.requireNonNull(etSearch.getText()).toString();
            initNet();
        });
    }

    @Override
    public void initData() {
        initNet();
        loadMore();
    }

    private void loadMore() {
        mPage += 1;
        mApi.agencyDocList(this, mPage, mRows, mKeyword, mDocType, flowId, new JsonCallback<Doc>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogTool.e(TAG, e);

            }

            @Override
            public void onResponse(Doc doc, int i) {
                mLastUpdateNum = doc.rows.size();
                if (mLastUpdateNum > 0) {
                    mPage++;
                    rowsList.addAll(doc.rows);
                    rvAdapter.notifyDataSetChanged();
                }
                if (LEmptyTool.isNotEmpty(refreshLayout))
                    refreshLayout.finishLoadMore();


                if (haveMore() && doc.rows.size() == mRows) {
                    refreshLayout.setEnableLoadMore(true);
                } else {
                    refreshLayout.setEnableLoadMore(false);
                }
            }
        });
    }

    private boolean haveMore() {
        return mLastUpdateNum > 0;
    }

    private void initNet() {
        statusView.onLoadingView();

        mPage = 1;
        mApi.agencyDocList(this, mPage, mRows, mKeyword, mDocType, flowId, new JsonCallback<Doc>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogTool.e(TAG, e);
                if (LEmptyTool.isNotEmpty(statusView))
                    statusView.onErrorView();
            }

            @Override
            public void onResponse(Doc doc, int i) {
                if (LEmptyTool.isEmpty(doc.rows)) {
                    statusView.onEmptyView();
                    return;
                }

                rowsList.clear();
                rowsList.addAll(doc.rows);
                mLastUpdateNum = doc.rows.size();
                rvAdapter.notifyDataSetChanged();
                if (LEmptyTool.isNotEmpty(refreshLayout)) {
                    refreshLayout.finishRefresh();
                    if (haveMore()) {
                        refreshLayout.setEnableLoadMore(true);
                    } else {
                        refreshLayout.setEnableLoadMore(false);
                    }
                }

                statusView.onSuccessView();

            }
        });
    }


    class RvAdapter extends BaseQuickAdapter<DocRows, BaseViewHolder> {
        //默认代办公文
        int type = 1;

        public void setType(int type) {
            this.type = type;
        }

        RvAdapter(List<DocRows> data) {
            super(R.layout.item_doc_rv, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, DocRows item) {
            helper.setText(R.id.tv_doc_type, item.documentType == 1 ? " 收文 " : "发文");
            helper.setText(R.id.tv_name, item.sender + " · ");
            helper.setText(R.id.tv_title, item.title);
            helper.setText(R.id.tv_handle, item.handleTitle);
            helper.setText(R.id.tv_time, item.createTime);

            if (item.documentType == 1) {
                helper.setBackgroundRes(R.id.tv_doc_type, R.color.colorPrimary);
            } else {
                helper.setBackgroundRes(R.id.tv_doc_type, R.color.textGreen);
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        LogTool.d(TAG + "unbinder.unbind();");

        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }
}
